package com.longrise.android.loaddata;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.util.Map;

public class AnsynHttpRequest 
{
	public static final int REQUEST_TIMEOUT = 10*1000;//设置请求超时10秒钟
	public static final int SO_TIMEOUT = 10*1000;  //设置等待数据超时时间10秒钟
	static final int POST = 1; // post 提交
	static final int GET = 2; // get 提交
    private static final String TAG = "AnsynHttpRequest";

	/**
	 * get请求
	 * @param callBack
	 * @param url
	 * @param serviceName
	 * @param map
	 * @param isCache
	 */
	public static void requestByGet(Context context,String appVersion,String url,String serviceName,Map<String, String> map,
			boolean isCache,ObserverCallBack callBack)
	{
		if(url == null || null== serviceName)
		{
			if(null != callBack)
			{
				callBack.back(null, url,null);
			}
			return;
		}
		
		//拼接请求地址
		StringBuffer stringBuffer = new StringBuffer(url);
		stringBuffer.append("/"+serviceName+"/query");
		
		if(map != null)
		{
			int i = 0;
			for (String key : map.keySet()) 
			{
				if(i == 0)
				{
					stringBuffer.append("?");
					stringBuffer.append(key + "=" + map.get(key));
				}
				else if(map.keySet().size()-1 == i)
				{
					stringBuffer.append(key + "=" + map.get(key));
				}
				else
				{
					stringBuffer.append(key + "=" + map.get(key) + "&");
				}
				i++;
			}
		}
		
		// 异步请求数据
		doAsynRequest(context,appVersion,GET, callBack, url, map,isCache);
	}
	
	/**
	 * post请求
	 * @param callBack
	 * @param url
	 * @param serviceName
	 * @param map
	 * @param isCache
	 */
	public static void requestByPost(Context context,String appVersion,String url,String serviceName,Map<String, String> map,
			boolean isCache,ObserverCallBack callBack)
	{
		// 异步请求数据
		doAsynRequest(context,appVersion,POST, callBack, url+"/"+serviceName+"/query", map,isCache);
	}

	/**
	 * 开始请求
	 * @param sendType
	 * @param callBack
	 * @param url
	 * @param url
	 * @param map
	 * @param isCache
	 */
	private static void doAsynRequest(Context context,String appVersion,int sendType, ObserverCallBack callBack,
			String url, Map<String, String> map,
			boolean isCache) 
	{
		// 请求
		ThreadPoolUtils.execute(new MyRunnable(context,appVersion,sendType, callBack, url, map, isCache));
	}
}
